<?php
/**
 * Joomla! 1.5 component ArticleCashRewards
 *
 * @version $Id: listing.php 2009-05-10 01:47:01 svn $
 * @author Maverick
 * @package models
 * @subpackage ArticleCashRewards
 * @license GNU/GPL
 * Website: http://www.boddunan.com
 *
 * Review and approve the articles and assign points and cash rewards.
 * Users can see their articles and the points/cash rewards assigned in the front-end module.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

if(!class_exists('ContentHelperRoute')) require_once (JPATH_SITE . '/components/com_content/helpers/route.php');  

class ArticleCashRewardsModelWebLinks extends JModel {

	var $_total = null; 
	var $_pagination = null;
    var $_error = null;
	
	function __construct(){
	
		parent::__construct();
		global $mainframe, $option;
	
		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest($option.'.limitstart', 'limitstart', 0, 'int');

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

    function getWebLinks($status) {
	    
    	global $mainframe, $option;
    	
    	// Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
		$filter_order		= $mainframe->getUserStateFromRequest( "$option.filter_order",		'filter_order',		'aw.date_submitted',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option.filter_order_Dir",	'filter_order_Dir',	'DESC',		'word' );

        if(strcmp($filter_order, 'u.username')==0){
            $filter_order = 'u.username';
        }else {
            $filter_order = 'aw.date_submitted';
        }
		$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir;

		$query = 'SELECT aw.id AS id, aw.value as weblink, aw.date_submitted as d_submitted,'.
            ' aw.description AS description, aw.remarks AS remarks, u.username AS author FROM '.
            TABLE_ACR_WEBLINKS . ' aw LEFT JOIN #__users u ON aw.userid=u.id WHERE status=' . $status . $orderby;
//echo $query;

		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$rows = $db->loadObjectList();

		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;
		
		$result->rows = $rows;
		$result->lists = $lists;

		return $result;
    }
    
    function getWebLinkAndRelatedData($id, $domainOnly){
        global $mainframe, $option;

    	// Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$query = 'SELECT aw.id AS id, aw.value as weblink, aw.date_submitted as d_submitted,'.
            ' aw.description AS description, aw.remarks AS remarks, u.username AS author FROM '.
            TABLE_ACR_WEBLINKS . ' aw LEFT JOIN #__users u ON aw.userid=u.id WHERE aw.id=' . $id;

		$db->setQuery($query);
		$weblink = $db->loadObject();
        $rows = null;
        if(count($weblink) > 0){

            $filter = $weblink->weblink;
            if($domainOnly){
                $filter = parse_url($weblink->weblink, PHP_URL_HOST);
            }

            $query = 'SELECT aw.value as weblink, aw.date_submitted as d_submitted,'.
                ' aw.description AS description, aw.remarks AS remarks, u.username AS author,' .
                ' aw.cash_rewards as cash, aw.date_paid as date_paid, aw.status as status FROM '.
                TABLE_ACR_WEBLINKS . ' aw LEFT JOIN #__users u ON aw.userid=u.id WHERE'.
                ' aw.id !=' . $id . ' AND aw.value LIKE "%' . $filter . '%"';
//echo $query;
            $db->setQuery($query);
            $rows = $db->loadObjectList();
        }else{
            $this->_error = $db->getErrorMsg();
            return false;
        }

		$result->weblink = $weblink;
		$result->related = $rows;

		return $result;
    }

    function setApprovalStatus($cid, $status){
    	global $mainframe, $option, $acr_config;

		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$total	= count($cid);
		$cids	= implode(',', $cid);
        $default_cash = $acr_config[CONFIG_WEBLINK_CASH_CREDIT]['config_value'];
        if($default_cash == null || $default_cash == ''
            || (0+$default_cash < 0)){
            $this->_error = "Default cash rewards value is null or not set";
            return false;
        }
        if($status == STATUS_APPROVED){
            $query = 'UPDATE ' . TABLE_ACR_WEBLINKS . ' SET status=' . $status .
                ', cash_rewards=' . $default_cash .', date_paid=NOW() WHERE id IN (' . $cids . ')'.
                ' AND status !=' . $status;
        }else if($status == STATUS_REJECTED){
            $query = 'UPDATE ' . TABLE_ACR_WEBLINKS . ' SET status=' . $status .
                ', cash_rewards=0, date_paid=NOW() WHERE id IN (' . $cids . ')' .
                ' AND status !=' . $status;
        }
        $db->setQuery($query);
        if($db->query()){
            $query = 'SELECT u.email FROM ' . TABLE_ACR_WEBLINKS . ' aw LEFT JOIN #__users u'.
                ' ON aw.userid = u.id WHERE aw.id IN(' . $cids . ')';
            $db->setQuery($query);
            $emails = $db->loadResultArray();

            $article_title = ' Web Link ';
            $article_created = '';

            $email_sub = 'One or more weblinks ' ;
            $email_body = '';
            if($status == STATUS_APPROVED){
                $email_sub .= $acr_config[CONFIG_A_ARTICLE_EMAIL_SUB];
                $email_body = $acr_config[CONFIG_A_ARTICLE_EMAIL_BODY];
            }else{
                $email_sub .= $acr_config[CONFIG_R_ARTICLE_EMAIL_SUB];
                $email_body = $acr_config[CONFIG_R_ARTICLE_EMAIL_BODY];
            }
            if( count($emails) > 0){
                ArticlecashrewardsHelper::sendEmail(
                    '"' . $acr_config[CONFIG_SENDER_EMAIL] . '"',
                    '"' . $acr_config[CONFIG_SENDER_NAME]. '"',
                    $emails, '"' . $email_sub . '"', '"' . $email_body . '"');
            }
            return true;
        }else{
            return false;
        }
    }

    function getTotal($status){

        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(*) FROM ' . TABLE_ACR_WEBLINKS . ' WHERE status=' . $status;
        $db->setQuery( $query );
        $this->_total = $db->loadResult();
		return $this->_total;
	}
	  
	function getPagination($status){
        global $mainframe,$option;
		$pnls = JRequest::getVar( 'pnlimitstart', 'null');
		
		if($pnls == 'null'){
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal($status), 0, $this->getState('limit') );
		    $this->setState('limitstart', 0);
            $mainframe->setUserState("$option.filter_order", 'aw.date_submitted');
		}

		// Load the content if it doesn't already exist
		if (empty($this->_pagination)) {
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal($status), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}    

    function getError(){
        return $this->_error;
    }
}
?>